/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.gui.studenci;

import db.models.Student;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.WindowManager;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(
        dtd = "-//org.gui//StudentsList//EN",
        autostore = false
)
@TopComponent.Description(
        preferredID = "StudentsListTopComponent",
        //iconBase="SET/PATH/TO/ICON/HERE", 
        persistenceType = TopComponent.PERSISTENCE_ALWAYS
)
@TopComponent.Registration(mode = "leftSlidingSide", openAtStartup = false)
@ActionID(category = "Window", id = "org.gui.StudentsListTopComponent")
@ActionReference(path = "Menu/Window" /*, position = 333 */)
@TopComponent.OpenActionRegistration(
        displayName = "#CTL_StudentsListAction",
        preferredID = "StudentsListTopComponent"
)
@Messages({
    "CTL_StudentsListAction=Lista studentów",
    "CTL_StudentsListTopComponent=Studenci",
    "HINT_StudentsListTopComponent=Zawiera listę wszystkich studentów"
})
public final class StudentsListTopComponent extends TopComponent {

    public StudentsListTopComponent() {
        initComponents();
        setName(Bundle.CTL_StudentsListTopComponent());
        setToolTipText(Bundle.HINT_StudentsListTopComponent());
        tabelaStudentow.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        setListener();
    }

    private void setListener() {
        tabelaStudentow.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent me) {
                JTable table = (JTable) me.getSource();
                Point p = me.getPoint();
                int row = table.rowAtPoint(p);
                if (me.getClickCount() == 2) {
                    StudentsListTopComponent window = (StudentsListTopComponent) WindowManager.getDefault().findTopComponent("StudentsListTopComponent");
                    String imie = table.getValueAt(row, 1).toString();
                    String nazwisko = table.getValueAt(row, 2).toString();
                    String email = table.getValueAt(row, 3).toString();
                    Integer indeks = (Integer) table.getValueAt(row, 4);
                    DodajEdytujStudentaPanel panel = new DodajEdytujStudentaPanel(imie, nazwisko, email, indeks);
                    Object[] options = {
                        "Edytuj", "Anuluj"
                    };
                    int input = JOptionPane.showOptionDialog(window, panel, "Edytuj studenta", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
                    if (input == JOptionPane.OK_OPTION) {
                        panel.editStudent((Integer) table.getValueAt(row, 0));
                    }
                }
            }
        });
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        tabelaStudentow = new javax.swing.JTable();

        setLayout(new java.awt.BorderLayout());

        tabelaStudentow.setModel(new StudentsTableModel());
        jScrollPane2.setViewportView(tabelaStudentow);

        add(jScrollPane2, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable tabelaStudentow;
    // End of variables declaration//GEN-END:variables
    @Override
    public void componentOpened() {
        //Jeśli komponent się otwiera trzeba załadować do niego dane
        StudentsListTopComponent window = this;
        TableModel model = window.getTabelaStudentow().getModel();
        clearTable((DefaultTableModel) window.getTabelaStudentow().getModel());
        List<Student> list = Student.getAll();
        int rowId = 0;
        for (Student s : list) {
            model.setValueAt(s.getId(), rowId, 0);
            model.setValueAt(s.getImie(), rowId, 1);
            model.setValueAt(s.getNazwisko(), rowId, 2);
            model.setValueAt(s.getEmail(), rowId, 3);
            model.setValueAt(s.getIndeks(), rowId, 4);
            rowId++;
        }
        hideIdColumn();
    }

    private void hideIdColumn() {
        TableColumn column = tabelaStudentow.getColumn("Id");
        column.setMinWidth(0);
        column.setMaxWidth(0);
        column.setPreferredWidth(0);
    }

    private void clearTable(DefaultTableModel model) {
        int rowCount = model.getRowCount();
        for (int i = 0; i < rowCount; i++) {
            model.removeRow(0);
        }
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    public JTable getTabelaStudentow() {
        return tabelaStudentow;
    }

}
